package com.by.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.by.common.crud.BaseServiceImpl;
import com.by.entity.sys.Role;
import com.by.mapper.sys.RoleMapper;
import com.by.service.sys.RoleService;
import com.by.utils.AssertsUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Transactional
    @Override
    public int save(Role entity) {
        //生成id
        String id = UUID.randomUUID().toString();
        entity.setId(id);
        //保存角色
        int rs = super.save(entity);
        if (rs == 0)
            AssertsUtils.rollback("保存失败");
        //判断是否有菜单权限
        if (AssertsUtils.isNotNull(entity.getAll())) {
            //保存角色权限(全选 )
            baseMapper.saveRoleMenu(id, entity.getAll(), 0);
        }

        if (AssertsUtils.isNotNull(entity.getHalf())) {
            baseMapper.saveRoleMenu(id, entity.getHalf(), 1);
        }

        return rs;
    }


    @Transactional
    @Override
    public int update(Role entity) {
        //根据角色id删除所有权限
        baseMapper.deleteByRoleId(entity.getId());

        //判断是否有菜单权限
        if (AssertsUtils.isNotNull(entity.getAll())) {
            //保存角色权限(全选 )
            baseMapper.saveRoleMenu(entity.getId(), entity.getAll(), 0);
        }

        if (AssertsUtils.isNotNull(entity.getHalf())) {
            baseMapper.saveRoleMenu(entity.getId(), entity.getHalf(), 1);
        }
        return super.update(entity);
    }

    @Override
    public List queryAuth(String id) {
        return baseMapper.queryAuth(id);
    }

    @Override
    public int deleteLogic(String id) {
        return baseMapper.deleteLogic(id);
    }

    @Override
    public List queryRole() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name");
        return baseMapper.selectMaps(queryWrapper);
    }
}
